<?php

namespace Biz\service\trade;

use Doraemon\pockets\point\tradePoint;
use Biz\pockets\serviceTrait\_Async;
use Doraemon\tools\Log as toolsLog;
use Biz\tools\Amount as toolAmount;
use Biz\pockets\constInterface\ActivityInfo as constActivityInfo;
/**
 * @deprecated
 */
class Integral
{
    use _Async;
    //积分抵扣档位阶梯
    const DEDUCTION_LADDER_MIN = 500;
    //商品成交金额每满100元抵扣500积分
    const ONE_HUNDRED_CAN_USE = 500;


    //积分兑换比例100积分=1元
    const CONVERSION_RATIO = 100;
    //订单总金额最低多少元可以使用积分
    const ORDER_IN_GOODS_AMOUNT = 100;

    /**
     * 计算sku使用的积分
     * @param $uid
     * @param array $skuAmountList sku列表
     *              [
     *                  'shopId'=>
     *                      [
     *                          "skuId"=>[
     *                          "amount"=>"skuPrice*buyNum",
     *                          "promo_id"=> 1,
     *                          "promo_type"=> 1,
     *                          ]
     *                      ]
     *              ]
     * @return array
     */

    public static function calUseInOrder($integral, $skuAmountList)
    {
        $result = [
        'data' => [],
        'sum' => 0,
        'discount' => 0,
        'msg' => ''
    ];

        //排序，按sku 价格低的升序排（解决最后一个sku 价格最低，平摊积分钱数大于商品购买价格）
        foreach ($skuAmountList as $shopId => $skuList) {
            $skuAmountSort = [];
            foreach ($skuList as $skuId => $row) {
                $skuAmountSort[] = $row['amount'];
                $row['sku_id'] = $skuId;
                $skuList[$skuId] = $row;
            }
            array_multisort($skuAmountSort, SORT_ASC, $skuList);
            $shopSkuList = [];
            foreach ($skuList as $row) {
                $shopSkuList[$row['sku_id']] = $row;
            }
            $skuAmountList[$shopId] = $shopSkuList;
        }

        $hasLimitTimeRobbing = false;
        //计算总共有多少个SKU参与计算
        $totalSku = 0;
        $goodsAmount = 0;
        foreach ($skuAmountList as $shopId => $skuList) {
            foreach ($skuList as $skuId => $row) {
                if ($row['promo_id'] && $row['promo_type'] == constActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB) {
                    //排除限时抢的商品价格 限时抢商品不参与积分抵扣
                    $hasLimitTimeRobbing = true;
                } else {
                    $skuAmount = $row['amount'];
                    $goodsAmount = bcadd($goodsAmount, $skuAmount, 2);
                    $totalSku = $totalSku + 1;
                }
            }
        }
        if ($integral < self::DEDUCTION_LADDER_MIN) {
            $result['msg'] = sprintf('共%d积分，满%d积分可用', $integral, self::DEDUCTION_LADDER_MIN);//不可抵扣 (分不足)
            return $result;
        }
        //判断订单商品总金额是否符合最低要求
        if ($goodsAmount < self::ORDER_IN_GOODS_AMOUNT) {
//            if ($hasLimitTimeRobbing) {
//                $result['msg'] = sprintf('共%d积分，购物满%d可抵扣(限时购商品不可使用积分)', $integral, self::ORDER_IN_GOODS_AMOUNT);//不可抵扣 (金额不足100) 限时购商品不可使用积分
//                return $result;
//            } else {
            $result['msg'] = sprintf('共%d积分，购物满%d可抵扣', $integral, self::ORDER_IN_GOODS_AMOUNT);//不可抵扣 (金额不足100)
            return $result;
//            }
        }
        //计算订单商品总金额可以使用的最低积分数
        $totalUse = min((int)($goodsAmount / self::ORDER_IN_GOODS_AMOUNT) * self::DEDUCTION_LADDER_MIN, (int)($integral / self::DEDUCTION_LADDER_MIN) * self::DEDUCTION_LADDER_MIN);
        //计算每个SKU可用的积分数
        $i = 0;
        $shopTotalIntegral = 0;
        foreach ($skuAmountList as $shopId => $skuList) {
            foreach ($skuList as $skuId => $row) {
                $skuAmount = $row['amount'];
                $skuIntegral = 0;
                if ($row['promo_id'] && $row['promo_type'] == constActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB) {
                    //排除限时抢的商品价格 限时抢商品不参与积分抵扣
                    $skuIntegral = 0;
                    $result['data'][$shopId]['list'][$skuId] = $skuIntegral;
                } else {
                    if ($i < $totalSku - 1) {
                        $skuIntegral = (int)(($skuAmount / $goodsAmount) * $totalUse);
                        $result['data'][$shopId]['list'][$skuId] = $skuIntegral;
                        $shopTotalIntegral += $skuIntegral;
                    } else {
                        $skuIntegral = $totalUse - $shopTotalIntegral;
                        $result['data'][$shopId]['list'][$skuId] = $skuIntegral;
                        break;
                    }
                    $i++;
                }
            }
            $result['data'][$shopId]['sum'] = array_sum($result['data'][$shopId]['list']);
            $result['sum'] += $result['data'][$shopId]['sum'];
        }
        $result['discount'] = toolAmount::format(($result['sum'] / self::CONVERSION_RATIO), 2);
        $result['msg'] = sprintf('共%d积分，可用%d积分抵扣¥%s', $integral, $result['sum'], $result['discount']);
        return $result;
    }

    /**
     * 获取用户积分
     * @param $uid
     * @return int
     */
    public static function getIntegral($uid)
    {
        $userIntegral = tradePoint::getPointAmount($uid);
        $integral = 0;
        if ($userIntegral && isset($userIntegral['amount'])) {
            $integral = $userIntegral['amount'];
        }
        return $integral;
    }

    /** 操作积分，扣积分、返积分
     * @param $uid 用户uid
     * @param $point 积分
     * @param $type 1：下单扣积分 2：下单失败回滚积分 3： 取消订单退积分
     */
    public static function operatePoint($uid, $point, $orderNo, $type)
    {
        if ($point) {
            self::_async($uid, $point, $orderNo, $type);
        }
    }

    public static function _async_operatePoint($uid, $point, $orderNo, $type)
    {
        if ($type == 1) {
            $res = tradePoint::consume($uid, $point, $orderNo, 'order.' . $orderNo);
            if (!$res) {
                toolsLog::order_integral_warning('提交订单扣积分失败', [
                    'result' => $res,
                    'operate' => 'consume',
                    'uid' => $uid,
                    'point' => $point,
                    'orderNo' => $orderNo,
                    'type' => $type,
                ]);
            }
        } else if ($type == 2 || $type == 3) {
            $res = tradePoint::refund($uid, $point, $orderNo, 'order-cancel.' . $orderNo);
            if (!$res) {
                $msg = '提交订单失败后回滚返积分失败';
                if ($type == 3) {
                    $msg = '取消订单退积分失败';
                }
                toolsLog::order_integral_warning($msg, [
                    'result' => $res,
                    'operate' => 'refund',
                    'uid' => $uid,
                    'point' => $point,
                    'orderNo' => $orderNo,
                    'type' => $type,
                ]);
            }
        }
    }

}